#include "LogManager.h"
#include "core/databasepool/databasepool.h"
#include <QSqlQuery>
#include <QVariant>
#include <QFile>
#include <QTextStream>
#include <QDebug>
#include <QSqlError>

// RecordLogTask 构造函数
RecordLogTask::RecordLogTask(LogManager* logManager, const QString& timestamp, const QString& logType, const QString& logLevel, const QString& content, int userId, int deviceId)
    : m_logManager(logManager), m_timestamp(timestamp), m_logType(logType), m_logLevel(logLevel), m_content(content), m_userId(userId), m_deviceId(deviceId) {}

// RecordLogTask 运行函数
void RecordLogTask::run() {
    QSqlDatabase db = DatabasePool::instance().getConnection();
    if (!m_logManager->recordSystemLogInternal(db, m_timestamp, m_logType, m_logLevel, m_content, m_userId, m_deviceId)) {
        qDebug() << "记录日志失败";
    }
    DatabasePool::instance().releaseConnection(db);
}

// ExportLogTask 构造函数
ExportLogTask::ExportLogTask(LogManager* logManager, const QString& filePath, const QString& startTime, const QString& endTime, const QString& logType)
    : m_logManager(logManager), m_filePath(filePath), m_startTime(startTime), m_endTime(endTime), m_logType(logType) {}

// ExportLogTask 运行函数
void ExportLogTask::run() {
    QSqlDatabase db = DatabasePool::instance().getConnection();
    if (m_filePath.endsWith(".csv")) {
        if (!m_logManager->exportLogsToCSVInternal(db, m_filePath, m_startTime, m_endTime, m_logType)) {
            qDebug() << "导出 CSV 日志失败: " << m_filePath;
        }
    } else if (m_filePath.endsWith(".txt")) {
        if (!m_logManager->exportLogsToTextInternal(db, m_filePath, m_startTime, m_endTime, m_logType)) {
            qDebug() << "导出文本日志失败: " << m_filePath;
        }
    }
    DatabasePool::instance().releaseConnection(db);
}

// 创建日志表
void LogManager::createLogTable() {
    QSqlDatabase db = DatabasePool::instance().getConnection();
    QSqlQuery query(db);
    // 执行创建日志表的SQL语句
    query.exec(R"(
        CREATE TABLE IF NOT EXISTS system_logs (
            log_id INTEGER PRIMARY KEY AUTOINCREMENT,
            timestamp TEXT NOT NULL,
            log_type TEXT NOT NULL,
            log_level TEXT NOT NULL,
            content TEXT NOT NULL,
            user_id INTEGER,
            device_id INTEGER,
            FOREIGN KEY (device_id) REFERENCES devices(device_id)
        )
    )");
    // 释放数据库连接
    DatabasePool::instance().releaseConnection(db);
}

// 构造函数，创建日志表
LogManager::LogManager(QObject* parent) : QObject(parent) {
    createLogTable();
}

// 析构函数
LogManager::~LogManager() {
    // 确保没有线程持有互斥锁
    m_mutex.lock();
    m_mutex.unlock();
}

// 内部记录系统日志函数
bool LogManager::recordSystemLogInternal(QSqlDatabase& db, const QString& timestamp, const QString& logType, const QString& logLevel, const QString& content, int userId, int deviceId) {
    QMutexLocker locker(&m_mutex);
    QSqlQuery query(db);
    query.prepare("INSERT INTO system_logs (timestamp, log_type, log_level, content, user_id, device_id) VALUES (:timestamp, :log_type, :log_level, :content, :user_id, :device_id)");
    query.bindValue(":timestamp", timestamp);
    query.bindValue(":log_type", logType);
    query.bindValue(":log_level", logLevel);
    query.bindValue(":content", content);
    query.bindValue(":user_id", userId);
    query.bindValue(":device_id", deviceId);
    if (!query.exec()) {
        qDebug() << "插入日志记录失败: " << query.lastError().text();
        return false;
    }
    return true;
}

// 记录系统日志
void LogManager::recordSystemLog(const QString& timestamp, const QString& logType, const QString& logLevel, const QString& content, int userId, int deviceId) {
    RecordLogTask* task = new RecordLogTask(this, timestamp, logType, logLevel, content, userId, deviceId);
    ThreadPool::instance().startTask(task);
}

// 查询日志（支持动态条件）
QList<QSqlRecord> LogManager::queryLogs(const QString& startTime, const QString& endTime, const QString& logType) {
    QMutexLocker locker(&m_mutex);
    QList<QSqlRecord> logRecords;
    QSqlDatabase db = DatabasePool::instance().getConnection();
    QSqlQuery query(db);

    // 动态构建SQL
    QString sql = "SELECT * FROM system_logs WHERE 1=1";
    if (!startTime.isEmpty() && !endTime.isEmpty()) {
        sql += " AND timestamp BETWEEN :startTime AND :endTime";
    }
    if (!logType.isEmpty()) {
        sql += " AND log_type = :log_type";
    }

    query.prepare(sql);
    if (!startTime.isEmpty() && !endTime.isEmpty()) {
        query.bindValue(":startTime", startTime);
        query.bindValue(":endTime", endTime);
    }
    if (!logType.isEmpty()) {
        query.bindValue(":log_type", logType);
    }

    if (!query.exec()) {
        qDebug() << "查询日志失败: " << query.lastError().text();
        DatabasePool::instance().releaseConnection(db);
        return logRecords;
    }

    while (query.next()) {
        logRecords.append(query.record());
    }
    DatabasePool::instance().releaseConnection(db);
    return logRecords;
}

// 内部导出日志为CSV函数
bool LogManager::exportLogsToCSVInternal(QSqlDatabase&, const QString& filePath, const QString& startTime, const QString& endTime, const QString& logType) {
    QMutexLocker locker(&m_mutex);
    QList<QSqlRecord> logRecords = queryLogs(startTime, endTime, logType);
    if (logRecords.isEmpty()) {
        qDebug() << "未查询到符合条件的日志记录，无法导出 CSV: " << filePath;
        return false;
    }
    QFile file(filePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qDebug() << "无法打开文件进行写入: " << filePath << ", 错误信息: " << file.errorString();
        return false;
    }
    QTextStream out(&file);
    // 写入表头
    out << "log_id,timestamp,log_type,log_level,content,user_id,device_id\n";
    for (const auto& record : logRecords) {
        out << record.value("log_id").toString() << ","
            << record.value("timestamp").toString() << ","
            << record.value("log_type").toString() << ","
            << record.value("log_level").toString() << ","
            << record.value("content").toString() << ","
            << record.value("user_id").toString() << ","
            << record.value("device_id").toString() << "\n";
    }
    file.close();
    return true;
}

// 导出日志为CSV
void LogManager::exportLogsToCSV(const QString& filePath, const QString& startTime, const QString& endTime, const QString& logType) {
    ExportLogTask* task = new ExportLogTask(this, filePath, startTime, endTime, logType);
    ThreadPool::instance().startTask(task);
}

// 内部导出日志为文本函数
bool LogManager::exportLogsToTextInternal(QSqlDatabase&, const QString& filePath, const QString& startTime, const QString& endTime, const QString& logType) {
    QMutexLocker locker(&m_mutex);
    QList<QSqlRecord> logRecords = queryLogs(startTime, endTime, logType);
    if (logRecords.isEmpty()) {
        qDebug() << "未查询到符合条件的日志记录，无法导出文本: " << filePath;
        return false;
    }
    QFile file(filePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qDebug() << "无法打开文件进行写入: " << filePath << ", 错误信息: " << file.errorString();
        return false;
    }
    QTextStream out(&file);
    // 写入表头
    out << "日志ID\t时间戳\t日志类型\t日志级别\t日志内容\t用户ID\t设备ID\n";
    for (const auto& record : logRecords) {
        out << record.value("log_id").toString() << "\t"
            << record.value("timestamp").toString() << "\t"
            << record.value("log_type").toString() << "\t"
            << record.value("log_level").toString() << "\t"
            << record.value("content").toString() << "\t"
            << record.value("user_id").toString() << "\t"
            << record.value("device_id").toString() << "\n";
    }
    file.close();
    return true;
}

// 导出日志为文本
void LogManager::exportLogsToText(const QString& filePath, const QString& startTime, const QString& endTime, const QString& logType) {
    ExportLogTask* task = new ExportLogTask(this, filePath, startTime, endTime, logType);
    ThreadPool::instance().startTask(task);
}
